import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
const db = getApp().globalData.db
const _ = db.command
// pages/desk/desk.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isChecked: false,
    selection: [],
    books: [],
    scrollHeight: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //获取组件内元素的信息
    const component = this.selectComponent(".nav-bar-top")

    let query = wx.createSelectorQuery().in(component)
    let nodeRef = query.select('.van-sticky-wrap')
    nodeRef.fields({
      size: true
    }, (res) => {
      this.setData({
        scrollHeight: wx.getSystemInfoSync().windowHeight - res.height
      })
    }).exec()


    this.query()
    this.data.books.forEach(v => {
      v.checked = false
    })
    this.setData({
      books: this.data.books,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTabBar().init()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onChecnked() {
    this.setData({
      isChecked: !this.data.isChecked
    })
  },

  //单元格点击
  onCellClick(ev) {
    const index = ev.currentTarget.dataset.i

    if (this.data.isChecked) {
      //置反
      this.data.books[index].checked = !this.data.books[index].checked
      if (this.data.books[index].checked) {
        //保存被选择的图书
        this.data.selection.push(this.data.books[index]._id)
      } else {
        //过滤未选中的书
        this.data.selection = this.data.selection.filter(v => {
          return v !== this.data.books[index]._id
        })
      }
    } else {
      wx.navigateTo({
        url: '/pages/detail/detail?id=' + this.data.books[index]._id, //携带参数，跳转页面
      })
    }

    //重新赋值数据
    this.setData({
      books: this.data.books,
      selection: this.data.selection
    })
  },

  //删除
  onDelete() {
    Dialog.confirm({
      title: '删除',
      message: '确认删除选中数据吗？',
    })
      .then(() => {
        Toast.loading({
          message: '删除中...',
          forbidClick: true,
        });
        db.collection("books").where({
          _id: _.in(this.data.selection)
        }).remove().then(res => {
          this.query()
        }).catch(err => {
          console.log(err);
        }).finally(() => {
          Toast.clear(true)
        })
      })
      .catch(() => {
        // on cancel
      });
  },
  query() {

    db.collection("books").get().then(res => {
      this.setData({
        books: res.data
      })
    }).catch(err => {
      console.log(err);
    })
  }
})